package cn.le.netty.util;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class ConnectionUtil {

    private static final Map<String, ChannelHandlerContext> CHANNEL_MAP = new ConcurrentHashMap<>();

    /**
     * 缓存链接
     * @param ip
     * @param port
     * @param ctx
     */
    public static void active(String ip,int port,ChannelHandlerContext ctx){
        String key = getKey(ip,port);
        CHANNEL_MAP.put(key,ctx);
    }

    /**
     * 退出操作
     * @param ip
     * @param port

     */
    public static void exit(String ip,int port){
        String key = getKey(ip,port);
        ChannelHandlerContext ctx = CHANNEL_MAP.get(key);
        if (ctx != null){
            CHANNEL_MAP.remove(key);
            ctx.close();
        }
    }

    /**
     * 获取连接
      * @param ip
     * @param port
     * @return
     */
    public static ChannelHandlerContext get(String ip,int port){
        return CHANNEL_MAP.get(getKey(ip,port));
    }

    private static String getKey(String ip,int port){
        return (ip + ":" + port);
    }

}
